package servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import bean.Tarefa;

import dao.TarefaDao;

/**
 * Servlet implementation class servletToDoList
 */
public class servletToDoList extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public servletToDoList() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String instrucoes = request.getParameter("instrucoes");
		if(instrucoes.equals("cadastrar"))
		{
			inserirTarefa(request);
			RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
			rd.include(request, response);
		}
		else if(instrucoes.equals("deletar"))
		{
			deletarTarefa(request);
			RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
			rd.include(request, response);
		}
		else if(instrucoes.equals("marcar"))
		{
			String[] tarefas = request.getParameterValues("tarefaPendentes");
			List<Tarefa> tarefaFeita = new ArrayList<Tarefa>();
			if(tarefas!=null){
				for(int i=0; i< tarefas.length; i++)
				{
				if(TarefaDao.buscarTarefa(tarefas[i]) != null)
				tarefaFeita.add(TarefaDao.buscarTarefa(tarefas[i]));
				
				}
				
				for(int i = 0; i < tarefaFeita.size(); i++){
					tarefaFeita.get(i).setPendente(false);
					TarefaDao.modificarTarefa(tarefaFeita.get(i));
				}
			}
			RequestDispatcher rd = request.getRequestDispatcher("listaDeTarefas.jsp");
			rd.include(request, response);
			
		}
		
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}
		
	
	private void inserirTarefa(HttpServletRequest request)
	{
		String novaTarefa = request.getParameter("tarefa");
		Tarefa tarefa = new Tarefa();
		tarefa.setDataTipoDate(new Date());
		tarefa.setData(tarefa.getData());
		tarefa.setTarefa(novaTarefa);
		tarefa.setPendente(true);
		
		TarefaDao.adicionarTarefa(tarefa);
	}
	
	private void deletarTarefa(HttpServletRequest request)
	{
		String tarefaDeletada = request.getParameter("id");
		Tarefa tarefa = new Tarefa();
		tarefa.setId(Long.parseLong(tarefaDeletada));
		
		
		TarefaDao.deletarTarefa(tarefa);
		
	}
	

}
